package com.youhome.service.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.youhome.common.exception.CustomException;
import com.youhome.common.response.ResultCode;
import com.youhome.service.mapper.OrderItemMapper;
import com.youhome.service.mapper.OrderMapper;
import com.youhome.service.mapper.ProductMapper;
import com.youhome.service.model.*;
import com.youhome.service.service.BUserService;
import com.youhome.service.service.OrderService;
import com.youhome.utils.OrderUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * Created by chen365 on 2017/9/13.
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private BUserService userService;

    @Autowired
    private ProductMapper productMapper;


    @Override
    public PageInfo<Order> selectByUserId(Long userId, int page, int pageSize) throws Exception {
        PageHelper.startPage(page, pageSize);
        List<Order> list = orderMapper.selectByUserID(userId);
        return new PageInfo<Order>(list);
    }

    @Override
    public Order selectByOrderNo(Principal principal, String orderNo) throws CustomException {
        Order order = orderMapper.selectByOrderNo(orderNo);

        if (order == null) {
            throw new CustomException(ResultCode.ILLEGAL_OPERATION);
        }
        Long userId = principal.getUser().getUserId();

        if (order.getUserId() != userId) {
            throw new CustomException(ResultCode.ILLEGAL_OPERATION);
        }
        return order;
    }

    @Override
    @Transactional
    public String submitOrder(Principal principal, Long productId, String ip) throws CustomException {

        Product product = productMapper.selectByPrimaryKey(productId);

        //一次只能购买一份，所以总价与单价一样；
        BigDecimal price = product.getPrice();//单价
        BigDecimal amount = price; //总价

        String orderNo = new OrderUtils().createOrderNo();
        Long userId = principal.getUser().getUserId();

        Order order = new Order();
        order.setUserId(userId);
        order.setAmount(amount);
        order.setOrderno(orderNo);
        order.setCtime(new Date());
        order.setStatus(0);//未支付
        order.setIp(ip);
        order.setReportNumber(product.getQuantity());

        int order_success = orderMapper.insertSelective(order);

        //一次只能购买一份，所以总价与单价一样；
        int number = 1;

        OrderItem orderItem = new OrderItem();

        orderItem.setOrderno(orderNo);
        orderItem.setProductId(productId);
        orderItem.setPrice(price);
        orderItem.setAmount(price.multiply(BigDecimal.valueOf(number)));
        orderItem.setStatus(1);
        orderItem.setCtime(new Date());
        orderItem.setNumber(1);//一份
        int item_success = orderItemMapper.insertSelective(orderItem);

        if (order_success == 1 && item_success == 1) {
            return orderNo;
        } else {
            throw new CustomException(ResultCode.FAIL);
        }
    }

    @Override
    public Integer orderPay(Order order) throws Exception {
        return userService.updateReportCount(order.getReportNumber(), order.getUserId());
    }

    @Override
    @Transactional
    public boolean orderPaySuccess(Order order, Integer pay_type) throws Exception {

        Order order1 = new Order();
        order1.setOrderno(order.getOrderno());
        order1.setStatus(5); //状态,0：未支付，1：已支付，2：用户取消，4：系统取消，5：订单完成
        if (pay_type != null) {
            order1.setPayType(pay_type); //支付类型，1.支付宝，2.微信
        }
        if (userService.updateReportCount(order.getReportNumber(), order.getUserId()) == 1
                && orderMapper.updateByPrimaryKeySelective(order1) == 1) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public int selectStatusByOrderNo(String orderNo) throws Exception {
        return orderMapper.selectStatusByOrderNo(orderNo);
    }

    @Override
    public PageInfo<Order> selectByUserId(Principal principal,Integer pageNumber, Integer pageSize) throws CustomException {
        if (pageNumber == null || pageNumber < 1) {
            pageNumber = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        PageHelper.startPage(pageNumber, pageSize);

        Long userId = principal.getUser().getUserId();
        List<Order> orders = orderMapper.selectByUserID(userId);
        return new PageInfo<>(orders);
    }

    @Override
    public void searchOrderStatus(Principal principal, String orderNo) throws CustomException {


        Order order = orderMapper.selectByOrderNo(orderNo);
        if (order == null) {
            throw new CustomException(ResultCode.ILLEGAL_OPERATION);
        }
        Long userId = principal.getUser().getUserId();
        if (order.getUserId() != userId) {
            throw new CustomException(ResultCode.ILLEGAL_OPERATION);
        }
        if (!order.getStatus().equals(5)) {
            throw new CustomException(ResultCode.FAIL_PAY);
        }

    }

    @Override
    public Order selectByOrderNo(String orderNo) {
        return orderMapper.selectByOrderNo(orderNo);
    }
}
